package com.zyplayer.doc.manage.framework.processor;

import com.zyplayer.doc.manage.framework.filter.MdcHttpFilter;
import org.slf4j.MDC;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.Objects;

/**
 * 如果本项目中使用到 RestTemplate 调用其他系统，那么也需要将traceId传递过去
 */
@Component
public class MdcRestTemplateHttpProcessor implements BeanPostProcessor {
    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        if (bean instanceof RestTemplate) {
            ((RestTemplate) bean).getInterceptors()
                    .add((request, body, execution) -> {
                        String traceId = MDC.get(MdcHttpFilter.TRACE_ID);
                        if (Objects.nonNull(traceId)) {
                            request.getHeaders().add(MdcHttpFilter.TRACE_ID, traceId);
                        }
                        return execution.execute(request, body);
                    });
        }
        return bean;
    }
}
